package main

import (
	"fmt"
	"github.com/gpmgo/gopm/modules/log"
	"golang.org/x/net/context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/reflection"
	pb "grpc/proto"
	"io"
	"net"
)

const (
	port = ":50051"
)

type server struct {
}

func (s *server) ListFeatures(rect *pb.Rectangle, stream pb.Greeter_ListFeaturesServer) error {
	if err := stream.Send(&pb.Feature{Message: "testStrem1"}); err != nil {
		return err
	}
	if err := stream.Send(&pb.Feature{Message: "testStrem2"}); err != nil {
		return err
	}
	if err := stream.Send(&pb.Feature{Message: "testStrem3"}); err != nil {
		return err
	}
	return nil
}

func (s *server) RecordRoute(stream pb.Greeter_RecordRouteServer) error {
	var pointCount int32
	//startTime := time.Now()
	for {
		point, err := stream.Recv()
		if err == io.EOF {
			//endTime:=time.Now()
			return stream.SendAndClose(&pb.RouteSummary{
				Message: "endServer",
			})
		}

		if err != nil {
			return err
		}

		pointCount++
		fmt.Println("%s", point.Name)
	}

}

func (s *server) RouteChat(stream pb.Greeter_RouteChatServer) error {
	for {
		in, err := stream.Recv()
		if err == io.EOF {
			return nil
		}

		if err != nil {
			return err
		}

		fmt.Println("%s", in.Name)
		stream.Send(&pb.RouteNote{
			Name: "test Server Go",
		})
	}
}

func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
	fmt.Println("get client requset name:", in.Message)
	return &pb.HelloReply{Name: in.Message}, nil
}

func main() {
	lis, err := net.Listen("tcp", port)
	if err != nil {
		log.Fatal("failed to listen:%s", err)
	}

	s := grpc.NewServer()
	pb.RegisterGreeterServer(s, &server{})
	reflection.Register(s)
	if err := s.Serve(lis); err != nil {
		log.Fatal("failed to serve :%v", err)
	}

}
